﻿window['console']['log'] = function () {};
var dataOn = null;
var data = {
    t: "1559010885",
    r: "z2eG2RFma",
    z: "0E7E1911542C66EAA8081132D1CFDF5E"
};
$(function () {

    // 左侧列表点击切换
    // $(".pageLeftUl").find("li").each(function (index) {
    //     console.log(this);
    //     $(this).click(function () {
    //       $(".pageLeftUl li").remove("active");
    //       $(this).addClass("active");
    //     });
    //   });

    // let selectVal = $('select[name="hahha"]').val();
    // console.log(selectVal);
    // 获取列表页面下拉
    var T = new Promise((resolve, reject) => {
        $.ajax({
            url: url + "admin/getClassroomCategoryList",
            type: "post",
            dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            data: data,
            success: function (res) {
                var data = res.data;
                // console.log(res);
                if (res.code == 200) {
                    var arr = [];
                    for (var i = 0; i < res.data.length; i++) {
                        var item = `
              <option value="${res.data[i].id}">${res.data[i].name}</option>
              `
                        arr.push(item);
                        //console.log('88887'+res.data[i].name);
                    }
                    resolve(data)
                } else {
                    reject(error)
                }

                $("#classroomDropDown").append(arr);
                $('#addClassroomDropDown').append(arr);
                renderSelect();
            }
        });
    })
    // 请求列表
    Promise.all([T, P]).then(values => {
        //  分页加载
        // 班级管理分页
        var aa = values[0];
        var cc = values[1];
        var cc1 = cc[1];
        cc1.forEach((item, index) => {
            aa.forEach((item1, index1) => {
                if (item1.id == item) {
                    console.log('成功')
                    $('.cname').eq(index).text(item1.name)
                }
            })
        })
        // 分页数据
        var laypage = layui.laypage;
        laypage.render({
            elem: "test1",
            count: dataOn.total, //数据总数，从服务端得到
            limit: dataOn.per_page,
            theme: "#2F72D5",
            jump: function (obj, first) {
                // console.log(obj.curr);

                if (!first) {
                    getList(obj.curr);
                    //do something
                }
            }
        });
    });
    // 添加 && 编辑 班级
    $("button").attr("type", "button");
    $(document).on("click", '.addClass', function () {
        let val = $(this).text()
        // console.log(val);
        if (val == '编辑') {
            $('#addBtn').hide();
            $('#saveBtn').show();
            var id = $(this).parent().parent().children().eq(0).text();
            var name = $(this).parent().parent().children().eq(1).text();
            var classroomId = $(this).parent().parent().children().eq(8).children().eq(0).val();
            var classroomPrice = $(this).parent().parent().children().eq(3).text();
            var image = $(this).parent().next().children().eq(0).val();
            // 比对列表 编辑页面下拉
            $('#addClassroomDropDown').find('option').each(function () {
                let val = $(this).val()
                $(this).removeAttr('selected', 'selected')
                if (val == classroomId) {
                    $(this).attr('selected', 'selected')
                    renderSelect()
                }
            });
            $('#className').val(name);
            // $('select[name="categoryId"]').append() ￥1000
            var newClassroomPrice = classroomPrice.substr(1, classroomPrice.length - 1);
            // console.log(newClassroomPrice);
            $('#classroomId').val(id)
            $('#classPrice').val(newClassroomPrice);
            $('#show').attr('src', url + image).show();
            $('.uploadPictures span').hide();
        } else if (val == '添加') {
            $('#addBtn').show();
            $('#saveBtn').hide();
        }
        $(".classroomListContent").hide();
        $(".classroomListAdd").show();
        $(".backBtn").click(function () {
            $(".classroomListContent").show();
            $(".classroomListAdd").hide();
            document.getElementById("addform").reset();
            $('.imgShow').hide()
            $('.uploadPictures span').show();
            // $('#addClassroomDropDown option').prop('selected','selected')
        });
    });
    // 编辑修改课程
    $('#saveBtn').click(function () {
        console.log('修改');
        var img = $("#input_file")[0].files[0];
        var reader = new FileReader();
        reader.readAsBinaryString(img);
        //reader.readAsDataURL(img);
        reader.addEventListener("loadend", function () {
            var formElement = document.getElementById("addform");
            var formData = new FormData(formElement);
            formData.append("t", "1559010885");
            formData.append("r", "z2eG2RFma");
            formData.append("z", "0E7E1911542C66EAA8081132D1CFDF5E");
            formData.append("categoryId", $('#addClassroomDropDown').val());
            formData.append("classroomId", $('#classroomId').val()); // console.log(JSON.stringify(formData));
            $.ajax({
                url: url + "admin/updateClassroom",
                type: "POST",
                //contentType: "multipart/form-data",
                data: formData,
                processData: false,
                contentType: false,
                success: function (data, textStatus, jqXHR) {
                    // console.log(data);
                    $(".classroomListAdd").hide();
                    $(".AddSuccess").show();
                },
                error: function (jqXHR, textStatus, error) {
                    // console.log('error');
                }
            });
        });
    })

    // 开启、关闭班级
    // $(document).on("click", function () {
    //     $(".classroomOpen").each(function () {
    //         $(this).click(function () {
    //             let add = $(this).text();
    //             $(".mark").show();
    //             if (add == "开启") {
    //                 // $(".classroomOpen").text("关闭");
    //                 // ajax
    //                 $(".opneClass").show();
    //                 console.log(32);
    //             } else if (add == "关闭") {
    //                 $(".classroomOpen").text("开启");
    //                 $(".closeClass").show();
    //                 $(".opneClass").hide();
    //                 console.log(12);
    //             }
    //         });
    //     });
    // });

    // $(".removeClassBtn").click(function () {
    //     $(".mark").show();
    //     $(".removeClass").show();
    // });
    // $(".closeMark,.cancelMark").click(function () {
    //     $(".mark").hide();
    // });

    // 列表点击展开后跳页
    $(document).on('click', '.onList', function () {
        var newId = $(this).parent().parent().children().eq(0).text();
        var newTitle = $(this).parent().parent().children().eq(1).text();
        window.location.href = 'onCourseList.html?id=' + newId + "&title=" + newTitle;
    })
});
// 提交修改表单
$("#addBtn").click(function () {
    console.log('添加');
    let a = $("#className").val();
    let b = $("#classPrice").val();
    let selectVal = $('select[name="selectVal"]').val();
    if (a == "") {
        layer.alert("请输入班级名称", {
            title: d,
            icon: 2
        });
    } else if (b == "") {
        layer.alert("请输入班级价格", {
            title: d,
            icon: 2
        });
    } else {
        var img = $("#input_file")[0].files[0];
        var d = "错误提示";
        var reader = new FileReader();
        reader.readAsBinaryString(img);
        //reader.readAsDataURL(img);
        reader.addEventListener("loadend", function () {
            var formElement = document.getElementById("addform");
            var formData = new FormData(formElement);
            formData.append("t", "1559010885");
            formData.append("r", "z2eG2RFma");
            formData.append("z", "0E7E1911542C66EAA8081132D1CFDF5E");

            // formData.image = img;
            // console.log(formData.image);
            // console.log(typeof formData);
            // console.log(JSON.stringify(formData));
            $.ajax({
                url: url + "admin/addClassroom",
                type: "POST",
                contentType: "multipart/form-data",
                data: formData,
                processData: false,
                contentType: false,
                success: function (data, textStatus, jqXHR) {
                    // console.log(data);
                    $(".classroomListAdd").hide();
                    $(".AddSuccess").show();
                },
                error: function (jqXHR, textStatus, error) {
                    // console.log('error');
                }
            });
        });
    }
});
// 添加成功后继续添加和返回
$(".addClassBtn").click(function () {
    $(".AddSuccess").hide();
    $(".classroomListAdd").show();
    document.getElementById("addform").reset();
});
$(".returnClassBtn").click(function () {
    $(".AddSuccess").hide();
    $(".classroomListContent").show();
    document.getElementById("addform").reset();
});

// 获取列表页+分页
var P = new Promise((resolve, reject) => {
    function getList(page) {
        var newData = Object.assign({}, data);
        newData.page = page;
        $.ajax({
            url: url + "admin/getClassroomList",
            type: "post",
            dataType: "json",
            async: false,
            contentType: "application/x-www-form-urlencoded",
            data: newData,
            success: function (response) {
                dataOn = response.data;
                let data = response.data.data;
                let length = data.length;
                console.log(response);
                let arr = [];
                let arr2 = [];
                let arr5 = [];
                if (response.code == 200) {
                    for (i = 0; i < length; i++) {
                        // 日期转时间戳
                        function timestampToTime() {
                            let time = data[i].updatedTime;
                            var date = new Date(time * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
                            var Y = date.getFullYear() + '-';
                            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
                            var D = date.getDate() + ' ';
                            return Y + M + D;
                        }
                        timestampToTime();
                        let changeColor = "price";
                        let Indicator = '';
                        if (data[i].status == 'closed') {
                            Indicator = 'close'
                        } else {
                            Indicator = 'open'
                        }
                        if (data[i].price == 0) {
                            changeColor = "zero";
                        }
                        var classRoomListContent =
                            `
                              <tr>
                                  <td>${data[i].id}</td>
                                  <td>${data[i].title}</td>
                                  <td class="cname"></td>
                                  <td class="${changeColor}">${
              data[i].price == 0 ? "免费" : "￥" + data[i].price
            }</td>
                                  <td class="assOn"><span class='${Indicator}'></span>${
                                    data[i].status == "closed" ? "关闭" : "已上线"
                                  }</td>
                                  <td>${timestampToTime()}</td>
                                  <td class="courseOperation"><a class="onList">展开</a><a class="addClass">编辑</a><a class="removeClassBtn">删除</a><a
                                  class="classroomOpen">${
                                    data[i].status == "closed" ? "关闭" : "开启"
                                  }</a></td>
                                  <td><input type="hidden" value="${data[i].largePicture}"></td>
                                  <td><input type="hidden" value="${data[i].categoryId}"></td>
                              </tr>
                          `

                        arr2.push(data[i].categoryId)
                        arr.push(classRoomListContent);
                    }
                    resolve([dataOn, arr2]);
                } else {
                    reject(error);
                }
                $(".classroomListContent tbody").html(arr);
            }
        });
    }
    return getList();
});

function renderSelect() {
    layui.use("form", function () {
        var form = layui.form;
        form.render();
        //…
    });
}

function loadImg() {
    var reads = new FileReader();
    f = document.getElementById("input_file").files[0];
    reads.readAsDataURL(f);
    reads.onload = function (e) {
        $('.imgShow').show();
        $('.uploadPictures span').hide();
        document.getElementById("show").src = this.result;
    };
}